package com.LostAndFound.web.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.LostAndFound.service.FailureRecodListService;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class FailureRecordListServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	FailureRecodListService service = new FailureRecodListService();
	
	public void failureRecordListForEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String cid = request.getParameter("cid");
		if(cid==null) {
			cid = "all";
		}
		String whatFlag = request.getParameter("whatFlag");
		// 当前页
		int pageNumber = Integer.parseInt(request.getParameter("page"));
		// 每页总条数
		int pageSize = Integer.parseInt(request.getParameter("rows"));
		// 总记录数
		int total = service.getTotalRecordForEasyUI(cid,whatFlag);
		
		List<Map<String,Object>> mapList = service.failureRecordListForEasyUI(pageNumber,pageSize,cid,whatFlag);
		// 转换成json格式数据
		Gson gson = new Gson();
		String json = gson.toJson(mapList);
		// 遍历json数组，改变whatflag字段值
		JsonParser parser = new JsonParser();
		JsonElement jsonElement = parser.parse(json);
		JsonArray jsonArray = jsonElement.getAsJsonArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
			if(jsonObject.get("whatflag").getAsString().equals("0")) {
				jsonObject.remove("whatflag");
				jsonObject.addProperty("whatflag", "寻找失主");
			}else {
				jsonObject.remove("whatflag");
				jsonObject.addProperty("whatflag", "寻找失物");
			}
		}
		// 重新格式化json数据		
		String rows = gson.toJson(jsonElement);
		// 发送回页面
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"total\":"+total+",\"rows\":"+rows+"}");
	}

	public void handleDeleteFailureRecordForEasyUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String aid = request.getParameter("aid");
		boolean success = service.handleDeleteFailureRecordForEasyUI(aid);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write("{\"success\":"+success+"}");
	}
}